<?php

namespace App\Http\Controllers;

use App\Models\UserDetail;
use Illuminate\Http\Request;

class BaseController extends Controller
{
    //
    protected $user;
    protected $userId;

    public function __construct()
    {
        $this->user = auth('api')->user();
        if (!$this->user) {
            return $this->jsonResultFail('need login', 403);
        }
        $this->userId = $this->user->id;
    }

    public function jsonResultOk($data = ['msg' => 'success'])
    {
        return response()->json($data);
    }

    /**
     * @param string $msg
     * @param int $status
     * @return \Illuminate\Http\JsonResponse
     */
    public function jsonResultFail($msg = 'fail', $status = 400)
    {
        return response()->json(['msg' => $msg], $status);
    }

//$table->integer('level')->default(1);
//$table->integer('exp')->default(100);
//$table->integer('coin')->default(100);
//$table->integer('content')->default(0);
//$table->integer('album')->default(0);
//$table->integer('fans')->default(0);
//$table->integer('follow')->default(0);
//$table->integer('star')->default(0);
//$table->integer('discuss')->default(0);
//$table->integer('private_letter')->default(0);
//$table->integer('group')->default(0);
//$table->integer('group_notice')->default(0);

    private function pp(string $field)
    {
        $data = UserDetail::query()->where(['user_id' => $this->userId])->first();
        if ($data) {
            $data->$field = $data->$field + 1;
            return $data->save();
        }
        return false;
    }

    public function coinPP(int $number)
    {
        $data = UserDetail::query()->where(['user_id' => $this->userId])->first();
        if ($data) {
            $data->coin = (int)$data->coin + $number;
            return $data->save();
        }
        return false;
    }

    public function contentPP()
    {
        return $this->pp('content');
    }

    public function levelPP()
    {
        return $this->pp('level');
    }

    public function expPP()
    {
        $data = UserDetail::query()->where(['user_id' => $this->userId])->first();
        if ($data) {
            $data->exp = $data->exp + 100;
            // 如果经验足够升级 则
            // $this->levelPP();
            return $data->save();
        }
        return false;
    }

    public function albumPP()
    {
        return $this->pp('album');
    }

    public function fansPP()
    {
        return $this->pp('fans');
    }

    public function followPP()
    {
        return $this->pp('follow');
    }

    public function starPP()
    {
        return $this->pp('star');
    }

    public function discussPP()
    {
        return $this->pp('discuss');
    }

    public function privateLetterPP()
    {
        return $this->pp('private_letter');
    }

    public function groupPP()
    {
        return $this->pp('group');
    }

    public function group_notice()
    {
        return $this->pp('group_notice');
    }

}
